<template>
  <div class="breadcrumb">
    <!-- 导航栏部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- 默认样式紧挨着，这里的el-breadcrumb设置在全局样式文件 global.css中 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片主体区域 -->
    <el-card class="box-card">
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <!-- active 表示当前所在进度的索引值，从0开始 -->
      <!-- :active="activeIndex-0" 是为了让字符串转成数字，因为 el-tabs 标签的 value 值是name 的字符串值，
      所以这里需要将 name 存储的字符串转成 el-steps 读取的数字 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- el-tab-pane 的name 属性值会在点击后被赋予 el-tabs 的value 值，所以使用 v-model="activeIndex" 来绑定 el-steps 标签的 active属性值，以达到
      "点击el-tab-pane 标签  el-step 标签会同步变化 "-->
      <el-form
        :model="goodForm"
        :rules="goodRules"
        ref="goodFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- label-position="top" ：表单文字在输入框上面 -->
        <!-- before-leave：离开标签触发方法 -->
        <!-- tab-click：标签被点击事件 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked()"
        >
          <!-- :tab-position="'left'" tabs标签页位于左边 -->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="goodForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="goodForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- option指定数据源 -->
              <!-- prop指定配置对象 -->
              <!-- clearable：增加清除功能 -->
              <!-- v-model 存储的值是所有标签对应ID的集合，从一级开始一直到最后一级 -->
              <el-cascader
                clearable
                v-model="goodForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 遍历参数项 -->
            <el-form-item
              v-for="item in manyParamList"
              :label="item.attr_name"
              :key="item.attr_id"
            >
              <!-- 遍历参数值 -->
              <el-checkbox-group v-model="item.checkedManyParamList">
                <el-checkbox
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                  border
                  :label="item1"
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 遍历属性项 -->
            <el-form-item
              v-for="item in onlyParamList"
              :label="item.attr_name"
              :key="item.attr_id"
            >
              <!-- 遍历属性值 -->
              <el-checkbox-group v-model="item.checkedOnlyParamList">
                <el-checkbox
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                  border
                  :label="item1"
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action：上传的URL
            on-preview：单击图片的事件（预览）
            on-remove：图片移除的事件
            list-type：图片索列图的展示方式 -->
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="goodForm.goods_introduce"> </quill-editor>
            <el-button type="primary" class="addBtn" @click="addGood()"
              >提交</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="dialogVisible" width="30%">
      <img :src="imgURL" class="imgPreview" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  data() {
    return {
      // 进度条当前处于的标签索引下标（这里配合了 el-tabs 标签）
      activeIndex: "0",
      // 添加商品的表单数据
      goodForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      goodRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 10 个字符",
            trigger: "change",
          },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品种类", trigger: "blur" },
        ],
      },
      // 所有的分类数组
      cateList: [],
      // 级联选择器确定的ID数组
      props: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        // 鼠标放上去就展开，默认需要鼠标点击
        expandTrigger: "hover",
      },
      // 动态参数数组
      manyParamList: [],
      // 静态属性数组
      onlyParamList: [],
      // 选中的动态参数值集合
      checkedManyParamList: [],
      // 选中的静态属性值集合
      checkedOnlyParamList: [],
      // 图片上传的 URL
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 为upload 添加 token
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片URL
      imgURL: "",
      // 图片预览对话框显示参数
      dialogVisible: false,
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取所有的分类
    async getCateList() {
      const { data: res } = await this.$http.get(`categories`);
      if (res.meta.status != 200) {
        this.$http.message.error("分类获取失败!");
      }
      this.cateList = res.data;
    },
    // 级联选择器修改时触发
    handleChange() {
      // 如果不是三级菜单就清空
      if (this.goodForm.goods_cat.length !== 3) {
        this.goodForm.goods_cat = [];
        return;
      }
    },
    // 左侧标签离开时触发
    beforeTabLeave(activeName, oldActiveName) {
      // 要跳转的标签页， 跳转前的标签页
      if (oldActiveName === "0" && this.goodForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品种类！");
        return false;
      }
    },
    // 左侧标签被点击触发
    async tabClicked() {
      if (this.activeIndex === "1") {
        // 动态参数
        const { data: res } = await this.$http.get(
          `categories/${this.thirdCateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        // 将参数值转成数组
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals !== "" ? item.attr_vals.split(" ") : [];
        });

        if (res.meta.status != 200) {
          this.$message.error("商品参数查询失败！");
        }
        // 为了配合checkbox实现自定义选择的属性值，为每个对象添加选中的name属性
        res.data.forEach(item=>{
          item.checkedManyParamList = [];
        })
        this.manyParamList = res.data;
      } else if (this.activeIndex === "2") {
        // 静态属性
        const { data: res } = await this.$http.get(
          `categories/${this.thirdCateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        // 为了配合checkbox实现自定义选择的属性值，为每个对象添加选中的name属性
        res.data.forEach(item=>{
          item.checkedOnlyParamList = [];
        })
        // 将属性值转成数组
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals !== "" ? item.attr_vals.split(" ") : [];
        });

        if (res.meta.status != 200) {
          this.$message.error("商品属性查询失败！");
        }
        this.onlyParamList = res.data;
      }
    },
    // 查看图片详情
    handlePreview(file) {
      this.imgURL = file.response.data.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file) {
      // 移除的文件信息
      // 将图片路径从goodForm表单中存储的图片地址数组移除
      const i = this.goodForm.pics.findIndex(
        (x) => x.pic === file.response.data.tmp_path
      );
      this.goodForm.pics.splice(i, 1);
    },
    // 上传成功后触发
    handleSuccess(response) {
      this.goodForm.pics.push(response.data.tmp_path);
    },
    // 添加商品
    async addGood() {
      this.$refs.goodFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写必要的表单项！");

        // 处理 分类ID
        const cloneForm = _.cloneDeep(this.goodForm);
        cloneForm.goods_cat = cloneForm.goods_cat.join(",");
        // 处理参数属性项、参数属性值
        this.manyParamList.forEach((item) => {
          cloneForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.checkedManyParamList.join(" "),
          });
        });
        this.onlyParamList.forEach((item) => {
          cloneForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.checkedOnlyParamList.join(" "),
          });
        });
        const { data: res } = await this.$http.post(`goods`,cloneForm);
        if (res.meta.status != 201) {
          this.$message.error("商品添加失败！");
          return ;
        }
        this.$message.success("商品添加成功！");
        this.$router.push('/goods');
      });
    },
  },
  computed: {
    thirdCateId() {
      if (this.goodForm.goods_cat.length === 3) {
        return this.goodForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>

<style scoped lang="less">
.imgPreview {
  width: 100%;
}
.addBtn {
  margin-top: 10px;
}
</style>
